<template>
  <view class="wrap">
    <image src="/static/logo.png" mode="aspectFit" class="logo" />
    <!-- 登录表单 -->
    <u-form
      :model="loginForm"
      ref="loginFormRef"
      :error-type="['message']"
      class="loginForm"
    >
      <u-form-item label="用户名" prop="username" label-width="150rpx">
        <u-input v-model="loginForm.username" placeholder="请输入用户名" />
      </u-form-item>
      <u-form-item label="密码" prop="password" label-width="150rpx">
        <u-input
          type="password"
          v-model="loginForm.password"
          placeholder="请输入密码"
        />
      </u-form-item>
      <u-button type="success" shape="square" @click="login">登录</u-button>
      <u-button type="info" shape="square" @click="register">注册</u-button>
    </u-form>
    <!-- 显示toast提示 -->
    <u-toast ref="loginToastRef" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 15,
            message: "用户名必须在5-15位之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 18,
            message: "密码必须在3-18位之间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //   点击登录按钮
    login() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (valid) {
          const { data } = await this.$request({
            url: "/login",
            method: "POST",
            data: this.loginForm,
          });
          if (data.code === 200) {
            let token = data.object.tokenHead + " " + data.object.token;
            uni.setStorageSync("token", token);
            uni.switchTab({
              url: "/pages/home/index",
            });
          } else {
            return this.$refs.loginToastRef.show({
              title: data.message,
              type: "error",
            });
          }
        }
      });
    },

    // 点击注册按钮
    register() {
      uni.navigateTo({
        url: "/pages/register/index",
      });
    },

    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
    onReady() {
      this.$refs.loginFormRef.setRules(this.loginRules);
    },
  },
};
</script>

<style scoped lang="scss">
.wrap {
  .logo {
    width: 100%;
    height: 200rpx;
  }

  u-button {
    margin: 100rpx;
  }

  width: 100%;
  height: 100vh;
  padding: 50rpx;
}

</style>